package day3.demo3;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@RestController
@RequestMapping("/file")
public class FileController {
    //实际类型为CommonsMultipartFile 如果有多个文件传来，参数为MultipartFile[] file数组类型
    @PostMapping("/upload1")
    String up1(MultipartFile f, HttpSession session) throws IOException {
        String fileName = f.getOriginalFilename();
        System.out.println("文件名：" + fileName + ",类型：" + f.getContentType() + ",大小:" + f.getSize());
        //f.transferTo(new File("d:/abc.jpg"));
        String dir = new SimpleDateFormat("yyyyMMdd").format(new Date());

        //"."表示的是tomcat的bin目录
        File file = new File("./..");
        String path = file.getCanonicalPath() + "/upload/" + dir;//会忽略掉.和..这样的表示
        file = new File(path);
        //创建对应子目录
        file.mkdirs();
        f.transferTo(new File(file, fileName));

        //图片回显
        return "/up/" + dir + "/" + fileName;
    }
}